package com.example.serviceribbon.web;

import com.example.serviceribbon.service.HelloService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.nimbusds.jose.JOSEException;
import com.zhang.test.common.util.Constants;
import com.zhang.test.common.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpCookie;
import java.time.LocalDateTime;
import java.time.temporal.TemporalField;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("")
    public String index() {
        return "hello World";
    }

    @GetMapping("hi")
    @HystrixCommand(fallbackMethod = "hasError")
    public String hi(String name) {

        return helloService.hiService(name);
    }

    public String hasError(String name, Throwable throwable) {
        System.out.println(throwable.getMessage());
        return "哎呀，出错了";
    }

    @GetMapping("login")
    public String login(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", 10000);
        tokenMap.put("exp", System.currentTimeMillis() + 1000 * 60 * 60 * 24);
        String token = "token is empty";
        try {
            token = TokenUtil.getInstance().createToken(tokenMap);

            Cookie cookie = new Cookie(Constants.X_TOKEN, token);
            response.addCookie(cookie);

        } catch (JOSEException e) {
            e.printStackTrace();
        }
        return token;
    }


}
